package com.cennavi.minemapdemo.activity.exlayer;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.util.Config;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.NavigationLayer;
import com.minedata.minemap.overlay.NavigationOptions;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.minedata.minemap.overlay.NavigationOptions.NAVIGATION_CAP_ROUND;
import static com.minedata.minemap.overlay.NavigationOptions.NAVIGATION_JOIN_ROUND;

//导航线图层Demo
public class NavigationActivity extends AppCompatActivity {
    private MapView mapView;
    private static MineMap mineMap;
    private Handler mHandler = new Handler();
    private int timer;
    private NavigationLayer navigationLayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);

        setContentView(R.layout.activity_navigation);
        mapView = findViewById(R.id.mapView);
        mapView.setApiBaseUrl(Config.API_BASE_URL);
        mapView.setApiUrl(Config.API_URL);
        mapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(final MineMap mineMap) {
                NavigationActivity.mineMap = mineMap;
                mineMap.setStyleUrl(Config.BASE_URL + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {

                    @Override
                    public void onStyleLoaded(String s) {
                        //默认显示路况
                        mineMap.setTrafficShow(true);
                        //60秒刷新一次
                        mineMap.setTrafficRote(60);
                        addNavi();
                        timeRunable.run();
                    }
                });
                mineMap.setRepaint(false);
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(41.81092, 123.43445))
                                .zoom(11)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                //设置是否显示地图调试信息，默认是不显示
                mineMap.setDebugActive(false);
            }
        });
    }

    //计时器
    private Runnable timeRunable = new Runnable() {
        @Override
        public void run() {
            if (navigationLayer.isLayerExist()) {
                float progress = (float) (timer++ % 101) / 100;
                NavigationOptions options = (NavigationOptions) navigationLayer.getOptions();
                options.setProgress(progress);
                navigationLayer.update();
            }

            mHandler.postDelayed(this, 100);
        }
    };

    //添加导航线图层
    public void addNavi() {
        NavigationOptions options = new NavigationOptions("navigationlayer");
        options.setAlpha(1.0f);
        options.setWidth(8.0f);
        options.setAnimationDuration(2000);
        options.setAnimationMode(NavigationOptions.NAVIGATION_ANIMATION_MODE_SINGLE);
        options.setCapType(NAVIGATION_CAP_ROUND);
        options.setJoinType(NAVIGATION_JOIN_ROUND);
        options.setBottomColorEnabled(true);
        options.setBottomColor("#C0C0C0");
        options.setProgressMode(NavigationOptions.NAVIGATION_PROGRESS_MODE_LTE);
        options.setProgress(0);
        options.addAll(getPointsData());
        navigationLayer = mineMap.addLayer(options);
    }

    //获取路线数据
    public List<NavigationOptions.NavigationItem> getPointsData() {
        List<NavigationOptions.NavigationItem> items = new ArrayList<>();

        try {
            InputStream instream = getAssets().open("drive_data.csv");
            List<LatLng> points1 = new ArrayList<>();
            List<LatLng> points2 = new ArrayList<>();

            if (instream != null) {
                InputStreamReader inputreader = new InputStreamReader(instream);
                BufferedReader buffreader = new BufferedReader(inputreader);
                String line;

                while ((line = buffreader.readLine()) != null) {
                    String everyLine = line;
                    String[] strarray = everyLine.split(",");

                    double longitude = (double) Integer.parseInt(strarray[0]) / 100000;
                    double latitude = (double) Integer.parseInt(strarray[1]) / 100000;
                    if (points1.size() < 280) {
                        points1.add(new LatLng(latitude, longitude));
                    } else {
                        if (points2.size() == 0) {
                            points2.add(points1.get(points1.size() - 1));
                        }
                        points2.add(new LatLng(latitude, longitude));
                    }

                }
                instream.close();
                buffreader.close();
            }

            NavigationOptions.NavigationItem item1 = new NavigationOptions.NavigationItem(points1, "#3CB371");
            NavigationOptions.NavigationItem item2 = new NavigationOptions.NavigationItem(points2, "#9b29e7");
            items.add(item1);
            items.add(item2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return items;
    }

    @Override
    protected void onStart() {
        if (mapView != null) {
            mapView.onStart();
        }
        super.onStart();
    }

    @Override
    protected void onResume() {
        if (mapView != null)
            mapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        if (mapView != null)
            mapView.onPause();
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mapView != null)
            mapView.onStop();
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (mapView != null)
            mapView.onDestroy();
        super.onDestroy();
    }

    public void btnGradient(View view) {
        NavigationOptions options = (NavigationOptions) navigationLayer.getOptions();
        if (options.getGradientEnabled()) {
            options.setGradientEnabled(false);
        } else {
            options.setGradientEnabled(true);
        }

        navigationLayer.update();
    }

    public void btnTest(View view) {
        mineMap.snapshot(new MineMap.OnSnapshotReadyCallback() {
            @Override
            public void onSnapshotReady(Bitmap snapshot) {
                //图片存放路径
                String sdCardDir = "/storage/emulated/0/Android/data/com.minedata.minemap/files/";

                try {
                    File dirFile = new File(sdCardDir);
                    if (!dirFile.exists()) {
                        dirFile.mkdirs();
                    }
                    //创建日期
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String sdfDate = sdf.format(date);
                    File file = new File(sdCardDir, "snapshot" + "(" + sdfDate + ")" + ".png");
                    FileOutputStream fos = new FileOutputStream(file);
                    snapshot.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
